package logic

import (
	"context"
	"ewaimai/waimairpc/cache"
	"fmt"
	"strconv"

	"ewaimai/waimairpc/internal/svc"
	"ewaimai/waimairpc/waimairpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsCarListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsCarListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsCarListLogic {
	return &GoodsCarListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsCarListLogic) GoodsCarList(in *waimairpc.GoodsCarListRequest) (*waimairpc.GoodsCarListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("cart:%d:*", in.UserId)
	keys, _ := cache.Rdb.Keys(l.ctx, key).Result()
	var carlist []*waimairpc.GoodsList
	for _, i2 := range keys {
		goodsMap, _ := cache.Rdb.HGetAll(l.ctx, i2).Result()
		price, _ := strconv.ParseFloat(goodsMap["price"], 64)
		num, _ := strconv.Atoi(goodsMap["num"])
		userId, _ := strconv.Atoi(goodsMap["userId"])
		goodsId, _ := strconv.Atoi(goodsMap["goodsId"])
		list := waimairpc.GoodsList{
			Name:    goodsMap["name"],
			Price:   float32(price),
			Num:     int64(num),
			Status:  1,
			UserId:  int64(userId),
			GoodsId: int64(goodsId),
		}
		carlist = append(carlist, &list)
	}

	return &waimairpc.GoodsCarListResponse{
		List: carlist,
	}, nil
}
